/*
 * Copyright (C) 2012 mAPPn.Inc
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.mol.market.demo.ui;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.RelativeLayout;
import com.mol.market.Constants;
import com.mol.market.R;
import com.mol.market.Session;
import com.mol.market.common.network.MarketAPI;
import com.mol.market.common.util.ImageUtils;
import com.mol.market.common.util.ScreenRules;
import com.mol.market.common.util.ScreenRules.Rules;
import com.mol.market.common.util.Utils;
import com.mol.market.demo.widget.BaseFragmentActivity;
import com.mol.market.demo.widget.LazyLoadFragmentWrapper;
import com.mol.market.ui.core.GridAdapter;
import com.mol.market.ui.core.GridAdapter.OnItemClickListener;
import com.mol.market.ui.core.LazyLoadAdapter;
import com.mol.market.ui_v4.MasterTabActivity;
import com.mol.market.ui_v4.ProductDetailActivity;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;

/**
 * @author Chaos	
 * @Description 首页
 * @date 2012-12-11 
 */
public class HomeFragment extends LazyLoadFragmentWrapper{
    
    private ImageView mHeaderFirst;
    private ImageView mHeaderSecond;
    
    private HashMap<String, Object> mProduct1;
    private HashMap<String, Object> mProduct2;
    
    @Override
    public void onStart() {
        super.onStart();
        MarketAPI.getTopRecommend(getSherlockActivity(), this);
    }
    
    @SuppressWarnings("unchecked")
    protected ArrayList<HashMap<String, Object>> getDataFromResult(int method,Object obj) {
        ArrayList<HashMap<String, Object>> data = (ArrayList<HashMap<String, Object>>) ((HashMap<String, Object>) obj)
                .get(Constants.KEY_PRODUCT_LIST);
        return data;
    }

    
    @Override
    protected LazyLoadAdapter initLazyLoadAdapter() {

       GridAdapter adapter = new GridAdapter(
                this,
                null,
                ScreenRules.getLayout(getWidthMatching(), Rules.Product),
                new String[]{
                        Constants.KEY_PRODUCT_ICON_URL,
                        Constants.KEY_PRODUCT_NAME,
                        Constants.KEY_PRODUCT_SUB_CATEGORY,
                        Constants.KEY_PRODUCT_IS_STAR,
                        Constants.KEY_PRODUCT_SIZE,
                        Constants.KEY_PRODUCT_PRICE,
                        Constants.KEY_PRODUCT_CORNER
                },
                new int[]{
                        R.id.iv_logo,
                        R.id.tv_name,
                        R.id.tv_description,
                        R.id.iv_star,
                        R.id.tv_size,
                        R.id.tv_charge,
                        R.id.corner
                });

        adapter.setNumColumns(ScreenRules.getNumColumns(getWidthMatching(), Rules.Product));
        
        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int pos, int realPos, HashMap<String, Object> item) {
                String pid = (String) item.get(Constants.KEY_PRODUCT_ID);
                String name = (String) item.get(Constants.KEY_PRODUCT_NAME);
                Intent detailIntent = new Intent(getActivity(), ProductDetailActivity.class);
                detailIntent.putExtra(Constants.EXTRA_PRODUCT_ID, pid);
                detailIntent.putExtra(Constants.EXTRA_SOURCE_TYPE, Constants.SOURCE_TYPE_GFAN);
                detailIntent.putExtra(Constants.EXTRA_PRODUCT_NAME, name);
                detailIntent.putExtra(Constants.EXTRA_SOURCE_TYPE, Constants.SOURCE_TYPE_GFAN);
                getActivity().startActivity(detailIntent);
                Utils.trackEvent(getApplicationContext(), Constants.GROUP_2, "推荐位>" + realPos);
            }
        });

        return adapter;
    }

    @Override
    protected void load() {
    	// TODO delete this
    	MarketAPI.insertHistoryInstall(getApplicationContext(), this, "com.baidu.input");
        MarketAPI.getHomeRecommend(getApplicationContext(), 
                this, getStart(), getSize(), false);
    }
    
    @Override
    protected boolean filter(int method) {
        if(method != MarketAPI.ACTION_GET_HOME_RECOMMEND){
            return true;
        }else{
            return false;
        }
    }
    
    @Override
    public void onClick(View v) {
        if (v.getId() == HeaderViewBuilder.ID_HEADER_GUESS_YOU_LIKE) {
            Utils.jumpToPage(
                    getActivity(), 
                    SecondFragmentActivity.class,
                    false,
                    new String[] { 
                        BaseFragmentActivity.KeyStore.KEY_ENTRY },
                    new Serializable[] { 
                        BaseFragmentActivity.KeyStore.TARGET_GENIUS });
            Utils.trackEvent(getApplicationContext(), Constants.GROUP_2, "猜你喜欢");
        } else if (v.getId() == HeaderViewBuilder.ID_HEADER_GEEK) {
            Utils.jumpToPage(getActivity(), MasterTabActivity.class, false);
            Utils.trackEvent(getApplicationContext(), Constants.GROUP_2, "达人专题");
        } else if (v.getId() == HeaderViewBuilder.ID_HEADER_BIGIMG_1) {
            handleTopItemClick(mProduct1);
            Utils.trackEvent(getApplicationContext(), Constants.GROUP_2, "推荐图1");
        } else if (v.getId() == HeaderViewBuilder.ID_HEADER_BIGIMG_2) {
            handleTopItemClick(mProduct2);
            Utils.trackEvent(getApplicationContext(), Constants.GROUP_2, "推荐图2");
        } else {
            super.onClick(v);
        }
        
    }
    
    private void handleTopItemClick(HashMap<String, Object> topItem) {

        if (topItem == null) {
            return;
        }

        String type = (String) topItem.get(Constants.KEY_RECOMMEND_TYPE);

        if (Constants.KEY_TOPIC.equals(type)) {
            // 专题项目，打开专题列表
            String topicId = (String) topItem.get(Constants.KEY_ID);
            String title = (String) topItem.get(Constants.KEY_PRODUCT_NAME);
            Utils.jumpToPage(getActivity(), SecondFragmentActivity.class, false,
                    new String[]{
                            BaseFragmentActivity.KeyStore.KEY_ENTRY,
                            Constants.KEY_TOPIC_ID,
                            Constants.KEY_TOPIC_NAME
                    },
                    new Serializable[]{
                            BaseFragmentActivity.KeyStore.TARGET_TOPICS,
                            topicId,
                            title
                    }
            );
        } else if (Constants.KEY_PRODUCT.equals(type)) {
            // 产品项目，直接去详细页
            String pid = (String) topItem.get(Constants.KEY_ID);
            String pName = (String) topItem.get(Constants.KEY_PRODUCT_NAME);
            Intent detailIntent = new Intent(getApplicationContext(), ProductDetailActivity.class);
            detailIntent.putExtra(Constants.EXTRA_PRODUCT_ID, pid);
            detailIntent.putExtra(Constants.EXTRA_PRODUCT_NAME, pName);
            startActivity(detailIntent);
        }
    }

    @Override
    protected View initHeaderView(LayoutInflater inflater) {
        View headerView = new HeaderViewBuilder(getWidth(), getDensity()).builder(getApplicationContext());
        mHeaderFirst  =  (ImageView) headerView.findViewById(HeaderViewBuilder.ID_HEADER_BIGIMG_1);
        ImageView guess  =  (ImageView) headerView.findViewById(HeaderViewBuilder.ID_HEADER_GUESS_YOU_LIKE);
        ImageView geek   =  (ImageView) headerView.findViewById(HeaderViewBuilder.ID_HEADER_GEEK);
        
        guess.setOnClickListener(this);
        geek.setOnClickListener(this);
        mHeaderFirst.setOnClickListener(this);
        
        /**
         * 如果大屏，就显示
         */
        View second = headerView.findViewById(HeaderViewBuilder.ID_HEADER_BIGIMG_2);
        if(second != null){
            mHeaderSecond = (ImageView) second;
            mHeaderSecond.setOnClickListener(this);
        }
       
        
        return headerView;
    }
    
    @Override
    protected boolean isCacheListWhenOriChange() {
        return false;
    }
    
    @Override
    protected void dealloc() {
        mHeaderFirst  = null;
        mHeaderSecond = null;
        mProduct1     = null;
        mProduct2     = null;
        super.dealloc();
    }
    
    @Override
    public void onSuccess(int method, Object obj) {
        
        if (method == MarketAPI.ACTION_GET_HOME_RECOMMEND) {
            super.onSuccess(method, obj);
        } else if (method == MarketAPI.ACTION_GET_TOP_RECOMMEND) {
            handleTopContent((ArrayList<HashMap<String, Object>>) obj);
        }
    }
    
    private void handleTopContent(ArrayList<HashMap<String, Object>> result) {

        if (result == null || result.size() == 0) {
            return;
        }

        mProduct1 = result.get(0);
        Session session = Session.get(getApplicationContext());
        session.setTopPid((String) mProduct1.get(Constants.KEY_ID));
        if (result.size() > 1) {
            mProduct2 = result.get(1);
        }

        if (mHeaderFirst != null) {
            ImageUtils.downloadHomeTopDrawable(getApplicationContext(),
                    (String) mProduct1.get(Constants.KEY_RECOMMEND_ICON), mHeaderFirst);
        }

        if (mHeaderSecond != null && mProduct2 != null) {
            ImageUtils.downloadHomeTopDrawable(getApplicationContext(),
                    (String) mProduct2.get(Constants.KEY_RECOMMEND_ICON), mHeaderSecond);
        }
    }
    
    @Override
    public void onError(int method, int statusCode) {
        super.onError(method, statusCode);
    }

    /**
     * HeaderView结构图(屏幕宽度小于等于400dp)：
     * -----------------------------------------
     *                          猜你喜欢
     *      BigImg1(服务器返回)  
     *                          达人专题
     * -----------------------------------------
     * 
     * HeaderView结构图(屏幕宽度大于400dp)：
     * --------------------------------------------------
     *                                         猜你喜欢
     *   BigImg1(服务器返回) BigImg2(服务器返回) 
     *                                         达人专题
     * --------------------------------------------------
     * 
     * 由于HeaderView面临如下3种情况，所以决定不使用XML实现。
     * 1.屏幕宽度不同，显示的数量不同。
     * 2.在不同屏幕上，控件所占大小不同，必须动态分配。
     * 3.必须保持原图比例（即不同宽度将会产生不同宽度的图）。
     * 
     * 所以，这里动态创建HeaderView
     * 
     * by Chaos at 2013/2/7
     */
    static class HeaderViewBuilder{
        /**
         * 决定于显示一个BigImg还是两个BigImg
         */
        private static final int STANDARD = 400; //(Dip)
        /**
         * 屏幕宽度
         */
        private int mWidth = -1;
        /**
         * 目标宽度，eg：720px or 1198px
         */
        private int mTargetWidth = -1;
        /**
         * 显示1 或者 2 个BigImg
         */
        private boolean mShowMore = false;
        /**
         * Root
         */
        private RelativeLayout root;
        
        /**
         * 大图1
         */
        public static final int ID_HEADER_BIGIMG_1       = 0x01;
        /**
         * 大图2
         */
        public static final int ID_HEADER_BIGIMG_2       = 0x02;
        /**
         * 猜你喜欢
         */
        public static final int ID_HEADER_GUESS_YOU_LIKE = 0x03;
        /**
         * 达人专题
         */
        public static final int ID_HEADER_GEEK           = 0x04;
        
        /**
         * @param width   屏幕宽度
         * @param density 屏幕密度
         */
        public HeaderViewBuilder(int width,float density){
            int standard = (int) (STANDARD * density);
            
            if(width <= standard){
                mShowMore = false;
                mTargetWidth = 720;
            }else{
                mShowMore = true;
                mTargetWidth = 1198;
            }
            
            this.mWidth = width;
        }
        
        
        public View builder(Context context){
            
            if(root != null){
                return root;
            }
            
//  When the width is 720px (360dp)
//          
//  source   (left margin) - (bigImg) - (mid margin) - (smallImg) - (right margin)
//  width(px)     24            440          12            220            24 
//   w:h                        2:1                       2.2:1
//
//When the width is 1198px (798.66666666666666666666dp)
//
//  source   (left margin) - (bigImg) - (mid margin)  - (bigImg) - (mid margin) - (smallImg) - (right margin)
//  width(px)     24           450           12            450          12            226           24 
//   w:h                       2:1                         2:1                       2.1:1  
//
//  expression
//        data                             real 
//  ----------------                 =   ---------  ====>  real = (screen * data) / 720
//  targetWidth(eg: 720px,1198px)         screen

            int padding    = expression(24);
            int bigImg     = expression(mShowMore?450:440);
            int midMargin  = expression(12);
            int smallImg   = expression(mShowMore?226:220);
            
            //if show more
            int bigImg2    = expression(450);
            int midMargin2 = expression(12);
            
            //pic - width : height
            int   bigImgRatio   = 2;
            float smallImgRatio = mShowMore?2.1f:2.2f;
            
            //Everything is ready
            root = new RelativeLayout(context);
            root.setBackgroundResource(R.drawable.list_item_background);
            root.setPadding(padding, padding, padding, padding);
            
            //add headerView (bigImg)
            ImageView header_bigImg_1 = new ImageView(context);
            header_bigImg_1.setScaleType(ScaleType.FIT_XY);
            header_bigImg_1.setId(ID_HEADER_BIGIMG_1);
            header_bigImg_1.setBackgroundResource(R.drawable.banner_loading);
            
            RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
                    bigImg, getHeightByRatio(bigImg, bigImgRatio));
            lp.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
            lp.addRule(RelativeLayout.ALIGN_PARENT_TOP);
            lp.setMargins(0, 0, midMargin, 0);
            root.addView(header_bigImg_1, lp);
            
            if(mShowMore){
                //add headerView2
                ImageView header_bigImg_2 = new ImageView(context);
                header_bigImg_2.setScaleType(ScaleType.FIT_XY);
                header_bigImg_2.setId(ID_HEADER_BIGIMG_2);
                header_bigImg_2.setBackgroundResource(R.drawable.banner_loading);
                
                lp = new RelativeLayout.LayoutParams(
                        bigImg, getHeightByRatio(bigImg2, bigImgRatio));
                
                lp.addRule(RelativeLayout.RIGHT_OF,ID_HEADER_BIGIMG_1);
                lp.addRule(RelativeLayout.ALIGN_PARENT_TOP);
                lp.setMargins(0, 0, midMargin2, 0);
                
                root.addView(header_bigImg_2,lp);
            }
            
            int anchor = mShowMore?ID_HEADER_BIGIMG_2:ID_HEADER_BIGIMG_1;
            
            //添加 猜你喜欢 
            ImageView guess_you_like = new ImageView(context);
            guess_you_like.setScaleType(ScaleType.FIT_XY);
            guess_you_like.setId(ID_HEADER_GUESS_YOU_LIKE);
            guess_you_like.setImageResource(R.drawable.selector_masking);
            guess_you_like.setBackgroundResource(R.drawable.guess_you_like);
            
            lp = new RelativeLayout.LayoutParams(
                    smallImg, getHeightByRatio(smallImg, smallImgRatio));
            lp.addRule(RelativeLayout.RIGHT_OF,anchor);
            lp.addRule(RelativeLayout.ALIGN_PARENT_TOP);
            
            root.addView(guess_you_like,lp);
            
            //添加达人专题 
            ImageView geek = new ImageView(context);
            geek.setScaleType(ScaleType.FIT_XY);
            geek.setId(ID_HEADER_GEEK);
            geek.setImageResource(R.drawable.selector_masking);
            geek.setBackgroundResource(R.drawable.geek);
            
            lp = new RelativeLayout.LayoutParams(
                    smallImg, getHeightByRatio(smallImg, smallImgRatio));
            lp.addRule(RelativeLayout.RIGHT_OF,anchor);
            lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
            
            root.addView(geek,lp);
            
//          finally...
            return root;
        }
        
        private int expression(int source){
            return (source * mWidth) / mTargetWidth;
        }
        
        private int getHeightByRatio(int width,int ratio){
            return width / ratio;
        }
        
        private int getHeightByRatio(int width,float ratio){
            return (int) (width / ratio);
        }
    }

}
